<template>
    <div id="login">
        <el-form :model="form" :rules="rules" ref="form">
            <div class="logo"></div>
            <el-form-item prop="mobile">
                <el-input placeholder="请输入手机号" v-model="form.mobile"></el-input>
            </el-form-item>
            <el-form-item prop="code">
                <el-input placeholder="请输入验证码" v-model="form.code"></el-input>
            </el-form-item>
            <el-form-item style="margin-top:-10px;" prop="agree">
                <el-checkbox label="我已阅读并同意用户协议和隐私条款" name="type" v-model="form.agree"></el-checkbox>
            </el-form-item>
            <el-form-item>
                <el-button  type="primary" style="width:100%;" @click="submitForm">登 录</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import { postLogin } from '@/api/user'
import { setToken } from '@/utils/storage'
export default {
  name: 'Login',
  data () {
    var validatePass = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请勾选用户协议'))
      } else {
        callback()
      }
    }
    return {
      form: {
        mobile: '13911111111',
        code: '246810',
        agree: false
      },
      rules: {
        mobile: [
          { required: true, message: '请输入手机号码', trigger: ['blur', 'change'] },
          { pattern: /^1[3-9]\d{9}/, message: '请输入11位手机号码', trigger: ['blur', 'change'] }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: ['blur', 'change'] },
          { pattern: /\d{6}/, message: '请输入6位验证码', trigger: ['blur', 'change'] }
        ],
        agree: [
          { validator: validatePass, trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  methods: {
    async submitForm () {
      try {
        await this.$refs.form.validate()
      } catch (error) {
        return this.$message.error('请注意检查用户信息是否填写完整')
      }
      try {
        const res = await postLogin({ mobile: this.form.mobile, code: this.form.code })
        if (res.status === 201) {
          setToken(res.data.data.token)
          this.$message.success('登录成功')
          this.$router.push('/')
        }
      } catch (error) {
        this.$message.error('登录失败')
      }
    }
  }
}
</script>

<style lang="less" scoped>
    #login {
        position: relative;
        height: 100%;
        background: url('~@/assets/login_bg.jpg');
        .el-form {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%,-50%);
            width: 400px;
            padding: 20px;
            background-color: #fff;
            border-radius: 10px;
            .logo {
                height: 57px;
                background: url('~@/assets/logo_index.png') no-repeat center;
                margin-bottom: 20px;
            }
        }
    }
</style>
